package com.example.beat;

import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: MALEXAND
 * Date: 17.04.12
 * Time: 13:31
 * To change this template use File | Settings | File Templates.
 */
public class BeatGenerator extends Thread implements IBeatGenerator {

    private static BeatGenerator beatGenerator = new BeatGenerator();

    private ArrayList<Observer> _observers = new ArrayList<Observer>();
    private boolean _isStarted = false;
    private int _beat;
    private int _timeout; //3000ms

    private BeatGenerator() {
        _beat = 0;
        _timeout = 10000;
        this.start();
    }
    public static BeatGenerator getInstance() {
        return beatGenerator;
    }

    public int getBeat() {
        return _beat;
    }

    public int getTimeout() {
        return _timeout;
    }

    public void setTimeout(int timeout) {
        this._timeout = timeout;
    }

    @Override
    public void run(){
        while (true) {
            if (_isStarted) {
                try {
                    Thread.sleep(_timeout);
                    this.incBeat();
                    this.notifyObservers();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    //TODO: calculate timeout after restart
                    Thread.sleep(_timeout);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void incBeat() {
        _beat++;
    }

    public void registerObserver(Observer observer) {
        _observers.add(observer);
    }

    public void removeObserver(Observer observer) {
        _observers.remove(observer);
    }

    public void notifyObservers() {
        int beat = _beat;
        for (Observer obs: _observers) {
            obs.update(beat);
        }
    }

    public void startGenerator() {
        _isStarted = true;
    }

    public void pauseGenerator() {
        _isStarted = false;
    }

    public void stopGenerator() {
        _isStarted = false;
        _beat = 0;
    }
}
